package com.party.admin.web.controller.competition;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.party.admin.biz.competition.CompProjectBizService;
import com.party.admin.utils.excel.ImportExcel;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.competition.CompetitionGroup;
import com.party.core.model.competition.CompetitionGroupResult;
import com.party.core.model.competition.CompetitionMember;
import com.party.core.model.competition.CompetitionSchedule;
import com.party.core.service.competition.*;
import com.party.core.utils.MyBeanUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 小组成绩控制器
 * Created by yifeng
 *
 * @date 2018/4/16 0016
 * @time 下午 17:45
 */
@Controller
@RequestMapping("/competition/groupResult")
public class CompetitionGroupResultController {
    @Autowired
    private ICompetitionGroupResultService competitionGroupResultService;
    @Autowired
    private ICompetitionScheduleService competitionScheduleService;
    @Autowired
    private ICompetitionGroupService competitionGroupService;
    @Autowired
    private ICompetitionMemberService competitionMemberService;
    @Autowired
    private ICompetitionResultService competitionResultService;
    @Autowired
    private CompProjectBizService compProjectBizService;

    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 增加成绩
     *
     * @param projectId
     * @return
     */
    @RequestMapping("toForm")
    public ModelAndView toForm(String projectId) {
        ModelAndView mv = new ModelAndView("competition/groupResultForm");

        // 赛程
        CompetitionSchedule t = new CompetitionSchedule();
        t.setProjectId(projectId);
        List<CompetitionSchedule> schedules = competitionScheduleService.listPage(t, null);
        mv.addObject("schedules", schedules);

        mv.addObject("projectId", projectId);
        return mv;
    }

    /**
     * 获取小组成绩
     *
     * @param projectId  项目id
     * @param scheduleId 日程id
     * @param isNew      是否第一次加载
     * @return
     */
    @ResponseBody
    @RequestMapping("getResultByProjectId")
    public AjaxResult getResultByProjectId(String projectId, String scheduleId, boolean isNew) {
        try {
            Map<String, Object> resultMap = Maps.newHashMap();
            // 成绩
            CompetitionGroupResult result = new CompetitionGroupResult();
            result.setProjectId(projectId);
            result.setScheduleId(scheduleId);
            List<CompetitionGroupResult> results = competitionGroupResultService.listPage(result, null);
            resultMap.put("results", results);

            if (isNew) {
                // 队伍
                List<CompetitionGroup> competitionGroups = competitionGroupService.list(new CompetitionGroup(projectId));
                resultMap.put("groups", competitionGroups);
            }
            return AjaxResult.success(resultMap);
        } catch (Exception e) {
            return AjaxResult.error("获取小组成绩异常");
        }
    }


    /**
     * 新增/编辑成绩
     *
     * @param cGroup        小组信息
     * @param bindingResult
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "saveResult", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveResult(CompetitionGroup cGroup, BindingResult bindingResult) {
        // 数据验证
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(description);
        }
        try {
            List<CompetitionGroupResult> results = cGroup.getResults();
            for (CompetitionGroupResult cr : results) {
                if (StringUtils.isEmpty(cr.getActualRange())) {
                    continue;
                }
                Double total = 0.0;
                if (StringUtils.isNotEmpty(cr.getHours())) {
                    Double hours = BigDecimalUtils.mul(Double.valueOf(cr.getHours()), 3600);
                    total = BigDecimalUtils.add(hours, total);
                }
                if (StringUtils.isNotEmpty(cr.getMinutes())) {
                    Double minutes = BigDecimalUtils.mul(Double.valueOf(cr.getMinutes()), 60);
                    total = BigDecimalUtils.add(minutes, total);
                }
                if (StringUtils.isNotEmpty(cr.getSeconds())) {
                    Double seconds = Double.valueOf(cr.getSeconds());
                    total = BigDecimalUtils.add(seconds, total);
                }
                cr.setSecondsResult(total + "");

                if (null == cr.getOpenStatus()) {
                    cr.setOpenStatus(YesNoStatus.NO_NEW.getCode());
                }
                if (StringUtils.isEmpty(cr.getId())) {
                    CompetitionGroupResult t = new CompetitionGroupResult();
                    MyBeanUtils.copyBeanNotNull2Bean(cr, t);
                    t.setProjectId(cGroup.getProjectId());
                    competitionGroupResultService.insert(t);
                } else {
                    CompetitionGroupResult t = competitionGroupResultService.get(cr.getId());
                    MyBeanUtils.copyBeanNotNull2Bean(cr, t);
                    competitionGroupResultService.update(t);
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存成绩失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存成绩失败");
        }
    }

    /**
     * 删除成绩
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteResult", method = RequestMethod.POST)
    public AjaxResult deleteResult(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        competitionGroupResultService.delete(id);
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping("initData")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult initData() {
        try {
            List<CompetitionGroup> groups = competitionGroupService.list(new CompetitionGroup());
            for (CompetitionGroup group : groups) {
                CompetitionMember query = new CompetitionMember();
                query.setGroupId(group.getId());
                List<String> cMemberIds = LangUtils.transform(competitionMemberService.list(query), new Function<CompetitionMember, String>() {
                    @Override
                    public String apply(CompetitionMember input) {
                        return input.getId();
                    }
                });
                if (cMemberIds.size() == 0) {
                    continue;
                }
                List<CompetitionSchedule> schedules = competitionScheduleService.findByProject(group.getProjectId());
                for (CompetitionSchedule schedule : schedules) {
                    Map<String, Object> resultMap = competitionResultService.findBySchedule(schedule.getId(), cMemberIds);
                    if (resultMap == null) {
                        continue;
                    }
                    String totalResult = resultMap.get("totalResult").toString();
                    if (StringUtils.isEmpty(totalResult)) {
                        continue;
                    }
                    int result = Double.valueOf(totalResult).intValue();
                    int hour = result / 3600;
                    int minute = (result % 3600) / 60;
                    int second = (result % 3600) % 60;

                    String totalDistance = resultMap.get("totalDistance").toString();
                    CompetitionGroupResult competitionGroupResult = new CompetitionGroupResult();
                    competitionGroupResult.setGroupId(group.getId());
                    competitionGroupResult.setProjectId(group.getProjectId());
                    competitionGroupResult.setScheduleId(schedule.getId());
                    competitionGroupResult.setSecondsResult(totalResult);
                    competitionGroupResult.setActualRange(totalDistance);
                    competitionGroupResult.setHours(hour + "");
                    competitionGroupResult.setMinutes(minute + "");
                    competitionGroupResult.setSeconds(second + "");
                    competitionGroupResultService.insert(competitionGroupResult);
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        }
    }


    @ResponseBody
    @RequestMapping("groupResultImport")
    public AjaxResult personResultImport(String projectId, HttpServletRequest request, MultipartFile uploadFile) {
        if (uploadFile.isEmpty()) {
            return AjaxResult.error("文件不存在！");
        }
        try {
            InputStream inputStream = uploadFile.getInputStream();
            Workbook workbook = ImportExcel.getWorkbook(inputStream, uploadFile.getOriginalFilename());
            new Thread(() -> compProjectBizService.groupResultImport(workbook, projectId, request.getSession().getId())).start();
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("解析文件异常", e);
            return AjaxResult.error("解析文件异常");
        }
    }
}
